package com.ja.openchat.ui.message;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Reader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.gyf.immersionbar.ImmersionBar;
import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.ActivityScanBinding;
import com.ja.openchat.viewmodels.ScanViewModel;
import com.zy.openchat.core.model.config.AppConfigInfo;
import com.zy.openchat.util.MediaUtils;
import com.zy.openchat.util.glide.GlideApp;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import cn.bingoogolapple.qrcode.core.QRCodeView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.base.BaseActivity;

public class ScanActivity extends BaseActivity<ActivityScanBinding,ScanViewModel> implements QRCodeView.Delegate {
    private static final String TAG = ScanActivity.class.getName();
    private boolean isLight = false;
    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_scan;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void setStatusBar() {
        BarUtils.setStatusBarLightMode(this, false);
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT);
    }

    @Override
    public ScanViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(ScanViewModel.class);
    }


    @Override
    public void initView() {
        ((ViewGroup.MarginLayoutParams)binding.ivBarBack.getLayoutParams()).topMargin = ImmersionBar.getStatusBarHeight(this);
        binding.ivBarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        binding.zxingBarcodeScanner.setDelegate(this);
        if (!hasFlash()) {
            binding.switchFlashlight.setVisibility(View.GONE);
        }else{
            binding.switchFlashlight.setActivated(false);
        }
        binding.switchFlashlight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isLight = !isLight;
                if (isLight) {
                    binding.zxingBarcodeScanner.openFlashlight();
                    binding.switchFlashlight.setActivated(true);
                } else {
                    binding.zxingBarcodeScanner.closeFlashlight();
                    binding.switchFlashlight.setActivated(false);
                }
            }
        });
        binding.switchAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaUtils.choosePhoto(ScanActivity.this,true);
            }
        });
        AppConfigInfo configInfo = AppConfigInfo.getAppWithoutLoginConfigInfo();

        if(configInfo!=null){
            if(!configInfo.can_see_qr_code){
                binding.myCodeView.setVisibility(View.INVISIBLE);
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

        binding.zxingBarcodeScanner.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别

        binding.zxingBarcodeScanner.startSpotAndShowRect(); // 显示扫描框，并开始识别
    }

    @Override
    protected void onStop() {
        binding.zxingBarcodeScanner.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
        super.onStop();
        hideProgress();
    }

    @Override
    protected void onDestroy() {
        binding.zxingBarcodeScanner.onDestroy(); // 销毁二维码扫描控件
        super.onDestroy();
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        Log.i(TAG, "result:" + result);
        vibrate();
        Intent intent = getIntent();
        if(intent != null)
        {
            Log.i(TAG, "intent:" + result);
            intent.putExtra("scanContent",result);
            setResult(RESULT_OK,intent);
            finish();
        }

    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {

    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Log.e(TAG, "打开相机出错");
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        binding.zxingBarcodeScanner.startSpotAndShowRect(); // 显示扫描框，并开始识别

//        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY) {
//            final String picturePath = BGAPhotoPickerActivity.getSelectedPhotos(data).get(0);
//            // 本来就用到 QRCodeView 时可直接调 QRCodeView 的方法，走通用的回调
//            binding.zxingBarcodeScanner.decodeQRCode(picturePath);
//        }
        List<String> albumPhotos = MediaUtils.getResultAlbumData(this,requestCode,resultCode,data);
        if(albumPhotos!=null&&albumPhotos.size()>0) {
            String localPah = albumPhotos.get(0);
            showProgress();
            GlideApp.with(ScanActivity.this)
                    .asBitmap()
                    .load(localPah)
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull @NotNull Bitmap bitmap, @Nullable @org.jetbrains.annotations.Nullable Transition<? super Bitmap> transition) {
                            Observable.create(new ObservableOnSubscribe<Result>() {

                                @Override
                                public void subscribe(@NotNull ObservableEmitter<Result> emitter) throws Exception {
                                    Result result = null;
                                    if(bitmap!=null){
                                        int width = bitmap.getWidth();
                                        int height = bitmap.getHeight();
                                        int[] pixels = new int[width * height];
                                        bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
                                        RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
                                        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
                                        Reader reader = new QRCodeReader();
                                        try {
                                            result = reader.decode(binaryBitmap);
                                        } catch (NotFoundException | ChecksumException | FormatException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                    if (result != null) {
                                        emitter.onNext(result);
                                    } else {
                                        emitter.onError(new Throwable());
                                    }

                                    emitter.onComplete();
                                }
                            })
                                    .subscribeOn(Schedulers.newThread())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new Consumer<Result>() {
                                        @Override
                                        public void accept(Result result) throws Exception {
                                            Intent intent = new Intent();
                                            intent.putExtra("scanContent", result.getText());
                                            setResult(Activity.RESULT_OK, intent);
                                            finish();
                                        }
                                    }, new Consumer<Throwable>() {
                                        @Override
                                        public void accept(Throwable throwable) throws Exception {
                                            ToastUtils.showShort(getString(R.string.recognition_failed));
                                            showProgress();
                                        }
                                    });

                        }
                    });
        }
    }


    //flash
    private boolean hasFlash() {
        return getApplicationContext().getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    }

}
